package com.schoolhelper.controller.activity;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import androidx.viewpager.widget.ViewPager;

import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.android.material.bottomnavigation.BottomNavigationView;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.schoolhelper.controller.adapter.MainRecyclerViewContentAdapter;
import com.schoolhelper.controller.adapter.MainRecyclerViewSelectLineAdapter;
import com.schoolhelper.controller.adapter.MainViewPagerAdapter;
import com.schoolhelper.controller.adapter.OnItemClickListener;
import com.schoolhelper.model.Model;
import com.schoolhelper.model.adaptermodel.MainRecyclerViewContent;
import com.schoolhelper.model.adaptermodel.MainRecyclerViewSelectLine;
import com.schoolhelper.model.dao.jsonparse.JsonParser;
import com.schoolhelper.model.dao.jsonparse.YyzControllerJsonParser;
import com.schoolhelper.model.dao.okhttp.RefactorRequestUrl;
import com.schoolhelper.model.entity.OrderImage;
import com.schoolhelper.model.vo.OrderImgVo;
import com.schoolhelper.utils.ImageUtils;
import com.schoolhelper.utils.MyCache;
import com.schoolhelper.utils.constant.Api;
import com.schoolhelper.utils.constant.YyzApi;

import java.time.DayOfWeek;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import lombok.SneakyThrows;

public class MainActivity extends AppCompatActivity implements OnItemClickListener, SwipeRefreshLayout.OnRefreshListener {

    private  final Integer SELECT_TYPE = 1;
    private final Integer CONTENT_TYPE = 2;
    private Integer SECLECT_POSITION  = 0;

    private MyCache myCache = new MyCache();
    List<OrderImgVo> orderImgVoList;
    List<OrderImgVo> orderImgVoTimeList = new ArrayList<>();
    List<Long> orderIdList = new ArrayList<>();
    String content;


    // 获取轮播图中的所有图片
    private int imageIds[] = {
            R.drawable.background1,
            R.drawable.background2
    };

    // 图片存储器，存储要放入轮播图中的图片
    private ArrayList<ImageView> images = new ArrayList<>();
    private ViewPager vp;
    private int currentItem; // 当前页面
    private ScheduledExecutorService scheduledExecutorService;

    private MainRecyclerViewSelectLineAdapter selectLineAdapter;

    // 选择行对象列表
    private List<MainRecyclerViewSelectLine> selectLineList = new ArrayList<>();

    private MainRecyclerViewContentAdapter contentAdapter;

    // 显示内容对象
    private List<MainRecyclerViewContent> contentList = new ArrayList<>();

    private List<MainRecyclerViewContent> SuoYouList = new ArrayList<>();
    private List<MainRecyclerViewContent> WaiMaiList = new ArrayList<>();
    private List<MainRecyclerViewContent> KuaiDiList = new ArrayList<>();
    private List<MainRecyclerViewContent> QiuShuList = new ArrayList<>();
    private List<MainRecyclerViewContent> DaYinList = new ArrayList<>();
    private List<MainRecyclerViewContent> DaiGouList = new ArrayList<>();


    private String selectname[] = new String[]{"所有", "外卖", "快递", "求书", "打印", "代购"};

    private BottomNavigationView mainNavigationView;
    private FloatingActionButton mainFabPost;

    private SwipeRefreshLayout swipeRefreshLayout;

    private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
             = item -> {
                 Intent intent;
                 switch (item.getItemId()) {
                     case R.id.main_navigation_main:
                         return false;
                     case R.id.main_navigation_message:
                         intent = new Intent(getApplicationContext(), ConversationListActivity.class);
                         startActivity(intent);
                         finish();
                         overridePendingTransition(0, 0);
                         return true;
                     case R.id.main_navigation_person:
                         intent = new Intent(getApplicationContext(), AccountActivity.class);
                         startActivity(intent);
                         finish();
                         overridePendingTransition(0, 0);
                         return true;
                     default:
                         Toast.makeText(getApplicationContext(), "error", Toast.LENGTH_SHORT).show();
                         return false;
                 }
             };

    @RequiresApi(api = Build.VERSION_CODES.Q)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        hideBottomUIMenu();

        // 轮播图自动滑动功能函数
        Slide();

        // 选择行的recyclerview配置
        initSelectLine();
        RecyclerView recyclerView = (RecyclerView) findViewById(R.id.main_select_recycle_view);// 获取操作的recyclerview
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);// 管理器实例化为Linear类型
        layoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);// 设置recyclerview为横向

        recyclerView.setLayoutManager(layoutManager);// 设置管理器
        selectLineAdapter = new MainRecyclerViewSelectLineAdapter(selectLineList);// adapter实例化

        selectLineAdapter.setItemClickListener(this, selectLineAdapter.getSelectType());// 设置item点击功能

        recyclerView.setAdapter(selectLineAdapter);// 为recyclerview设置adapter

        swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.main_content_refresh);

        // 内容初始化及RecyclerViewAdapter的配置
        initContent(contentList);

        swipeRefreshLayout.setOnRefreshListener(this);

        mainNavigationView = findViewById(R.id.main_bottom_view);
        mainNavigationView.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
        mainNavigationView.setSelectedItemId(R.id.main_navigation_main);

        mainFabPost = findViewById(R.id.main_fab_post);
        mainFabPost.setOnClickListener(v -> {
            toPostActivity();
        });
    }

    private void toPostActivity() {
        if (MyCache.read(getApplicationContext(), "userId") == null) {
            runOnUiThread(() -> {
                Toast.makeText(getApplicationContext(), "您需要先登录才能发布", Toast.LENGTH_SHORT).show();
            });
            Intent toLogin = new Intent(getApplicationContext(), LoginActivity.class);
            startActivity(toLogin);
        } else {
            Intent toPost = new Intent(getApplicationContext(), PostActivity.class);
            startActivity(toPost);
        }
    }

    protected void hideBottomUIMenu() {
        //隐藏虚拟按键，并且全屏
        if (Build.VERSION.SDK_INT > 11 && Build.VERSION.SDK_INT < 19) { // lower api
            View v = this.getWindow().getDecorView();
            v.setSystemUiVisibility(View.GONE);
        } else if (Build.VERSION.SDK_INT >= 19) {
            //for new api versions.
            View decorView = getWindow().getDecorView();
            int uiOptions = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY | View.SYSTEM_UI_FLAG_FULLSCREEN;
            decorView.setSystemUiVisibility(uiOptions);
        }
    }

    @RequiresApi(api = Build.VERSION_CODES.Q)
    @Override
    public void onRefresh() {

        System.out.println("***************************************************************");
        System.out.println("刷新一次");
        System.out.println("***************************************************************");

        SuoYouList.clear();
        WaiMaiList.clear();
        KuaiDiList.clear();
        QiuShuList.clear();
        DaYinList.clear();
        DaiGouList.clear();

        switch (SECLECT_POSITION){
            case 0:initContent(SuoYouList);
                break;
            case 1:initContent(WaiMaiList);
                break;
            case 2:initContent(KuaiDiList);
                break;
            case 3:initContent(QiuShuList);
                break;
            case 4:initContent(DaYinList);
                break;
            case 5:initContent(DaiGouList);
                break;
        }
        //停止刷新
        swipeRefreshLayout.setRefreshing(false);
        //刷新RecycleView
        contentAdapter.notifyDataSetChanged();
    }


    @SneakyThrows
    @RequiresApi(api = Build.VERSION_CODES.Q)
    private void initContent(List<MainRecyclerViewContent> initList) {

        System.out.println("***************************************************************");
        System.out.println("开始initCONTENT");
        System.out.println("***************************************************************");


        MyCache.write(getApplicationContext(), "orderImgList", null);


        // 将数据写进Cache
        saveInContent();

        // 从Cache中读出数据
        content = MyCache.read(getApplicationContext(), "orderImgList");

        // Json解析
        JsonParser jsonParser = new YyzControllerJsonParser();
        List<OrderImgVo> orderImgVoList1 = jsonParser.getList(content, OrderImgVo.class);

        for (OrderImgVo orderImgVo:orderImgVoList1) {

            // 获取图片地址的url的List
            List<OrderImage> list = orderImgVo.getOrderImages();

            // 因为要联网获取，所以要用线程去运行
            Callable<MainRecyclerViewContent> callable = new Callable<MainRecyclerViewContent>() {
                @Override
                public MainRecyclerViewContent call() throws Exception {
                    Bitmap bitmap = null;

                    if (list.get(0).getImageUrl() == null) {
                    } else {
                        bitmap = ImageUtils.GetLocalOrNetBitmap(list.get(0).getImageUrl(), getApplicationContext());
                    }
                    // 建立Content对象
                    MainRecyclerViewContent recyclerViewContent = new MainRecyclerViewContent(orderImgVo.getOrderId() ,bitmap, orderImgVo.getTitle(), orderImgVo.getDescription());

                    // 返回Content对象
                    return recyclerViewContent;
                }
            };

            // 获取线程中返回的对象，并添加到对象List中
            Future<MainRecyclerViewContent> recyclerViewContent = Model.getInstance().getGlobalThreadPool().submit(callable);
            contentList.add(recyclerViewContent.get());

            switch (orderImgVo.getType()){
                case "所有":SuoYouList = contentList;
                    break;
                case "外卖":WaiMaiList.add(recyclerViewContent.get());
                    break;
                case "快递":KuaiDiList.add(recyclerViewContent.get());
                    break;
                case "求书":QiuShuList.add(recyclerViewContent.get());
                    break;
                case "打印":DaYinList.add(recyclerViewContent.get());
                    break;
                case "代购":DaiGouList.add(recyclerViewContent.get());
                    break;
            }

        }

        RecyclerView content_recyclerview = (RecyclerView) findViewById(R.id.main_content_recycle_view);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);

        content_recyclerview.setLayoutManager(linearLayoutManager);
        contentAdapter = new MainRecyclerViewContentAdapter(initList);

        contentAdapter.setItemClickListener(this, contentAdapter.getContentType());

        content_recyclerview.setAdapter(contentAdapter);

        System.out.println("***************************************************************");
        System.out.println("结束initCONTENT");
        System.out.println("***************************************************************");

    }

    @SneakyThrows
    private void saveInContent() {

        // 实例化解析方法
        JsonParser jsonParser = new YyzControllerJsonParser();
        // 用hashMap存header
        Map<String, String> headers = new HashMap<>();
        orderImgVoList = RefactorRequestUrl.postThenGetList(
                Api.BASE_URL, YyzApi.ORDER_WITH_IMG, headers, null,
                OrderImgVo.class, jsonParser);

        orderImgVoTimeList.clear();
        for (int i = orderImgVoList.size() - 1; i >= 0; i--){
            OrderImgVo o = orderImgVoList.get(i);
            orderImgVoTimeList.add(o);
        }

        orderIdList.clear();
        // 获取对应orderID
        for (OrderImgVo orderImgVo: orderImgVoTimeList){
            Long orderId = orderImgVo.getOrderId();
            orderIdList.add(orderId);
        }

        String orderListJsonStr = new ObjectMapper().writeValueAsString(orderImgVoTimeList);
        // 将返回信息写入Cache
        myCache.write(getApplicationContext(), "orderImgList", orderListJsonStr);

    }

    @RequiresApi(api = Build.VERSION_CODES.Q)
    @Override
    public void onItemClick(int position, int type) {
//        Toast.makeText(this, "" + position, Toast.LENGTH_SHORT).show();
        // {"所有", "外卖", "快递", "求书", "打印", "代购"}
        if (type == SELECT_TYPE){

            SuoYouList.clear();
            WaiMaiList.clear();
            KuaiDiList.clear();
            QiuShuList.clear();
            DaYinList.clear();
            DaiGouList.clear();
            switch (position){
                case 0:initContent(SuoYouList);
                    SECLECT_POSITION = 0;
                break;
                case 1:initContent(WaiMaiList);
                    SECLECT_POSITION = 1;
                    break;
                case 2:initContent(KuaiDiList);
                    SECLECT_POSITION = 2;
                    break;
                case 3:initContent(QiuShuList);
                    SECLECT_POSITION = 3;
                    break;
                case 4:initContent(DaYinList);
                    SECLECT_POSITION = 4;
                    break;
                case 5:initContent(DaiGouList);
                    SECLECT_POSITION = 5;
                    break;
            }
        }
        if (type == CONTENT_TYPE){
//            Toast.makeText(this, "这是contents:" + orderIdList.get(position), Toast.LENGTH_SHORT).show();
            // {"所有", "外卖", "快递", "求书", "打印", "代购"}

            Intent intent = new Intent(getApplication(), DetailActivity.class);

            Bundle bundle = new Bundle();
            switch (SECLECT_POSITION){
                case 0:bundle.putLong("orderID", SuoYouList.get(position).getOrderId());
                    break;
                case 1:bundle.putLong("orderID", WaiMaiList.get(position).getOrderId());
                    break;
                case 2:bundle.putLong("orderID", KuaiDiList.get(position).getOrderId());
                    break;
                case 3:bundle.putLong("orderID", QiuShuList.get(position).getOrderId());
                    break;
                case 4:bundle.putLong("orderID", DaYinList.get(position).getOrderId());
                    break;
                case 5:bundle.putLong("orderID", DaiGouList.get(position).getOrderId());
                    break;
            }
            intent.putExtras(bundle);

            System.out.println("*-----------------------------------------------------------------------------------------------------------------");
            System.out.println(orderIdList.get(position));
            startActivity(intent);

        }
    }

    private void initSelectLine() {

        for(int i = 0; i < selectname.length; i++){
            MainRecyclerViewSelectLine selectLine = new MainRecyclerViewSelectLine(selectname[i]);
            selectLineList.add(selectLine);
        }
    }

    private void Slide() {

        // 将图片放入到存储器中
        for (int i = 0; i < imageIds.length; i++) {
            ImageView imageView = new ImageView(this);
            imageView.setImageResource(imageIds[i]);

            images.add(imageView);
        }

        //通过id绑定ViewPager，调用adapter进行处理
        vp = (ViewPager) findViewById(R.id.main_vp);
        vp.setAdapter(new MainViewPagerAdapter(images));

        vp.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }


    // 设置线程池，对轮播图活动进行延时操作，每三秒换一张图
    @Override
    protected void onStart() {
        super.onStart();
        scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();
        scheduledExecutorService.scheduleWithFixedDelay(new ViewPagerTask(), 3, 3, TimeUnit.SECONDS);
    }

    // 实现一个碎片的接口
    private class ViewPagerTask implements Runnable {
        @Override
        public void run() {
            currentItem = (currentItem+1)%imageIds.length;
            // 更新界面
            handler.obtainMessage().sendToTarget();
        }
    }

    // 在handler进行碎片跳转
    // setCurrentItem（position）根据position设置一个一个页面为当前页面
    Handler handler = new Handler(){
        @Override
        public void handleMessage(@NonNull Message msg) {
            vp.setCurrentItem(currentItem);
        }
    };

}